<template>
  <view class="app-container">
    <image class="background" src="/static/images/background.png" mode="aspectFill"></image>

    <view class="info" :style="{ marginTop: titleMargin + 'px' }">
      <image class="avatar" mode="aspectFill" @click="previewImg(info.avatar)" :src="info.avatar ? info.avatar : '/static/images/default_avatar.png'"></image>
      <block v-if="info.id">
        <view class="name-box">
          <view class="name">{{ info.nickname }}</view>
          <view class="rz-box" v-if="info.rz_status == 1">
            <image class="icon" src="/static/images/name_icon.png"></image>
            <text class="level-num" v-if="info.level_num > 0">{{ info.level_num }}</text>
          </view>
        </view>
        <view class="id">ID：{{ info.id_num }}</view>
      </block>
    </view>

    <view class="main-box">
      <view class="follow-box" v-if="applet_version == 1">
        <view class="tab-box" @click="goFollowMe">
          <view class="text">关注我的</view>
          <view class="count">（{{ info.follow_me_count ? info.follow_me_count : 0 }}）</view>
        </view>
        <view class="tab-box" @click="goMyFollow">
          <view class="text">我关注的</view>
          <view class="count">（{{ info.me_follow_count ? info.me_follow_count : 0 }}）</view>
        </view>
      </view>

      <view class="row" @click="goMyDetails" v-if="applet_version == 1">
        <image class="icon" src="/static/images/my_icon1.png"></image>
        <view class="text">我的资料</view>
      </view>
      <button open-type="contact" :plain="true" class="row">
        <image class="icon" src="/static/images/my_icon2.png"></image>
        <view class="text">联系我们</view>
      </button>
    </view>

    <view id="mask" v-if="show_login" @click.stop>
      <view class="mask-content" @click.stop>
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="nickname" class="input" placeholder="请输入昵称">
          </view>

          <view class="row" style="border-top: none">
            <view class="left">手机号</view>
            <button open-type="getPhoneNumber" :plain="true" @getphonenumber="getPhoneNumber" class="mobile-btn" v-if="!mobile">获取手机号</button>
            <block v-else>
              <input type="number" :value="mobile" name="mobile" style="display: none">
              <view class="input">{{mobile}}</view>
            </block>
          </view>

          <view class="agree-box">
            <button hover-class="none" :type="'mini'" :plain="true" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <button :plain="true" class="button cancel" @click="this.show_login = false">取消</button>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>

    <CustomTabBar :tabList="tabList" :currentTab="currentTab" @change="changeTab"/>
  </view>
</template>

<script>
import http from '@/utils/http'
import {initWebSocket} from '@/utils/function/ws'

export default {
  data() {
    return {
      tabList: [],
      currentTab: '',
      service_list: [],
      swiperIndex: 0, // 当前轮播图索引
      title: '',
      titleMargin: 0, // 动态顶部间距
      show_login: false,
      login_to_url: '',// 登录之后跳转的页面
      privacyContractName: '《喜到啦隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      mobile: '',
      info: [],
      applet_version: -1
    };
  },

  created() {
    var tab_list = uni.getStorageSync('tab_list');
    if (tab_list) this.tabList = tab_list;

    this.getTabList(); // 获取 TabList
    this.setDynamicMargin()
  },

  onShow() {
    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0;
    if (user_id == 0) uni.hideShareMenu();  // 隐藏系统分享按钮
  },
  onShareAppMessage() {
    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0;
    return {
      title: '喜到啦诚邀您的加入',
      path: '/pages/my/my?scene=' + user_id,
      imageUrl: http.config.baseURL + '/static/xcx/share.png'
    };
  },

  onLoad: function (options) {
    this.$http.post('/index/Api/getAppletVersion2').then(res => {
      this.applet_version = parseInt(res.data.data);
    })

    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0,
      scene_user_id = options.scene ? options.scene : uni.getStorageSync('scene_user_id');// 分享人的user_id

    if (scene_user_id > 0) uni.setStorageSync('scene_user_id', scene_user_id)

    if (!user_id) {
      uni.showLoading({
        title: '自动登录中...',
        mask: true
      })

      uni.login({
        success: result => {
          var code = result.code;

          this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
            uni.hideLoading();
            if (res.data.result === 1) {
              var user_id = res.data.data;
              uni.setStorageSync('user_id', user_id)
              var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;

              this.userCenter(user_id, scene_user_id)
            } else {
              this.show_login = true;
            }
          })
        }
      })
    } else {
      var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;
      this.userCenter(user_id, scene_user_id)
    }
  },

  methods: {
    getTabList() {
      this.$http.post('/index/Api/getTabbar').then(res => {
        if(JSON.stringify(this.tabList) !== JSON.stringify(res.data.data)){
          uni.setStorageSync('tab_list', res.data.data);
          this.tabList = res.data.data;
        }
        // 默认选中的 Tab
        this.currentTab = this.tabList[3].path;
      });
    },

    previewImg: function (img) {
      this.$common.previewImg(img);
    },

    goMyDetails: function () {
      uni.navigateTo({
        url: '/pages/my_details/my_details'
      })
    },

    changeTab(path) {
      this.currentTab = path;
      uni.redirectTo({url: path}); // 切换到指定的页面
    },
    setDynamicMargin() {
      const windowInfo = uni.getWindowInfo();
      this.titleMargin = windowInfo.statusBarHeight + 10; // 直接使用状态栏高度
    },

    userCenter: function (user_id, scene_user_id = 0) {
      this.$http.post('/index/Api/userCenter', {user_id, scene_user_id}).then(res => {
        if (res.data.result === 1) {
          this.info = res.data.data

          // 存储认证状态
          uni.setStorageSync('rz_status', res.data.data.rz_status);
          uni.setStorageSync('avatar', res.data.data.avatar);

          initWebSocket('wss://www.xidaola1314.com/wss')

          if(res.data.data.up_user_id > 0) uni.removeStorageSync('scene_user_id');

          if(res.data.data.show_step == 1){
            uni.reLaunch({
              url: '/pages/step/step'
            })
          }
        } else {
          this.$common.doErrorResult(res);
        }
      })
    },

    goFollowMe: function () {
      uni.navigateTo({
        url: '/pages/follow_me/follow_me'
      })
    },

    goMyFollow: function () {
      uni.navigateTo({
        url: '/pages/my_follow/my_follow'
      })
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result === 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    getPhoneNumber: function (e){
      var code = e.detail.code;
      this.$http.post('/index/Api/getMobile', {code}).then(res => {
        if (res.data.result === 1) {
          this.mobile = res.data.data
        }else{
          this.$common.doErrorResult(res)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result === 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result === 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.show_login = false;

                    var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;
                    this.userCenter(user_id, scene_user_id)
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                this.$common.doErrorResult(res);
              }
            })
          }
        })
      }
    },

  },
}
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 10rpx;

  button{
    border: none;
    padding: 0;
    margin: 0;
  }

  .info {
    display: flex;
    flex-direction: column;
    align-items: center;

    .avatar {
      width: 200rpx;
      height: 200rpx;
      border-radius: 200rpx;
    }

    .name-box {
      display: flex;
      margin-top: 20rpx;
      align-items: center;

      .name {
        font-size: 40rpx;
      }

      .rz-box{
        position: relative;
        .icon {
          width: 36rpx;
          height: 36rpx;
          margin-left: 10rpx;
        }
        .level-num{
          position: absolute;
          top: 10rpx;
          left: 16rpx;
          font-size: 18rpx;
          color: #fff;
          width: 20rpx;
          text-align: center;
          height: 20rpx;
          padding: 2rpx;
          line-height: 20rpx;
          border-radius: 50%;
          background: #c55f5f;
        }
      }
    }

    .id {
      font-size: 32rpx;
    }
  }

  .main-box {
    display: flex;
    align-items: center;
    flex-direction: column;
    width: 100%;
    height: 65vh;
    border-radius: 40rpx 40rpx 0 0;
    //background: linear-gradient(to bottom, rgba(228, 67, 35, 0.8), rgba(216, 216, 216, 0.2));
    background: $main-background;
    overflow: hidden;
    position: absolute;
    bottom: 0;

    .follow-box {
      display: flex;
      justify-content: space-between;
      width: 70%;
      padding: 70rpx 0;

      .tab-box {
        flex: 1;
        text-align: center;
        font-size: 40rpx;
        color: $main-blank;

        .count {
          margin-top: 10rpx;
        }
      }
    }

    .row {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      width: 80%;
      margin-bottom: 60rpx;

      .icon {
        width: 60rpx;
        height: 60rpx;
      }

      .text {
        font-size: 40rpx;
        margin-left: 40rpx;
        color: $main-blank;
      }
    }

  }
}
</style>
